import React, { useState, useEffect, useMemo } from 'react';
import { message, Modal, Tooltip } from 'antd';
import { ReactSortable } from 'react-sortablejs';
import { useRequest } from '@/hooks';
import { saveCommonEntrance } from '@/services/notice/homePage';
import Icon from '@/components/IconPro';

import styles from './index.less';

const QuickCheckModal = ({ visible, onOk, onCancel, selectedModule = [], unselectedModule = [] }) => {
    const [selectWorkflow, setSelectedWorkflow] = useState([]);
    const [unselectWorkflow, setUnselectedWorkflow] = useState([]);
    const [isOnlyOne, setIsOnlyOne] = useState(true);

    // 保存
    const { run: confirmPersonalWorkflow, loading: confirmLoading } = useRequest(params => saveCommonEntrance(params), {
        manual: true
    });

    // 存储状态副本
    useEffect(() => {
        setSelectedWorkflow(selectedModule);
        setUnselectedWorkflow(unselectedModule);
        setIsOnlyOne(selectedModule?.length <= 1);
    }, [selectedModule, unselectedModule]);

    // 至少保留一项
    useEffect(() => {
        setIsOnlyOne(selectWorkflow?.length <= 1);
    }, [selectWorkflow]);

    // 完成
    const handleOk = async () => {
        let unselectedIds = [];

        unselectWorkflow.forEach(item => {
            const result = item.itemList.map(i => ({ itemId: i.itemId }));
            unselectedIds = [...unselectedIds, ...result];
        });

        if (onOk) {
            const { code, msg } = await confirmPersonalWorkflow({
                checkList: selectWorkflow.map((item, index) => ({ sort: index + 1, itemId: item.itemId })),
                uncheckList: unselectedIds
            });
            if (code === 10000) {
                onOk();
            } else {
                message.error(msg);
            }
        }
    };

    // 取消
    const handleCancel = () => {
        if (onCancel) {
            onCancel();
        }
    };

    const unselectCount = useMemo(() => unselectWorkflow.reduce((a, b) => a + b.itemList.length, 0), [
        unselectWorkflow
    ]);

    // 添加
    const handleAdd = (entry, category) => {
        const result = unselectWorkflow.map(item => {
            if (item.category === category) {
                return {
                    ...item,
                    itemList: item.itemList.filter(i => i.itemId !== entry.itemId)
                };
            }
            return item;
        });
        setUnselectedWorkflow(result);
        setSelectedWorkflow([...selectWorkflow, { ...entry, category }]);
    };

    // 删除
    const handleRemove = item => {
        const result = selectWorkflow.filter(i => i.itemId !== item.itemId);
        const unselectedResult = unselectWorkflow.map(i => {
            if (i.category === item.category) {
                return {
                    ...i,
                    itemList: [...i.itemList, item]
                };
            }
            return i;
        });
        setSelectedWorkflow(result);
        setUnselectedWorkflow(unselectedResult);
    };

    return (
        <Modal
            visible={visible}
            width={952}
            title="添加常用入口"
            confirmLoading={confirmLoading}
            onOk={handleOk}
            onCancel={handleCancel}
            okText="提交"
            className={styles.quickCheckModal}
        >
            <div className={styles.quickCheckModalWrapper}>
                <div className={styles.quickCheckCard}>
                    <p>拖拽可调整顺序（最少保留1个）：</p>
                    <div className={styles.workflowSortable}>
                        <ReactSortable
                            key="processDefinitionId"
                            group="quickCheckWorkflow"
                            list={selectWorkflow}
                            setList={setSelectedWorkflow}
                            draggable=".notDisabled"
                            animation={150}
                        >
                            {selectWorkflow.map((item, index) => (
                                <div
                                    className={`${styles.sortableItem} ${isOnlyOne ? styles.disabled : 'notDisabled'}`}
                                    // eslint-disable-next-line react/no-array-index-key
                                    key={`${item.itemId}-${index}`}
                                >
                                    <span>{item.itemName}</span>
                                    <Icon.Button
                                        className={styles.lintGrayColor}
                                        icon="iconclose_o"
                                        dark
                                        disabled={isOnlyOne}
                                        onClick={() => handleRemove(item)}
                                    />
                                </div>
                            ))}
                        </ReactSortable>
                    </div>
                </div>
                {unselectCount > 0 && (
                    <div className={`${styles.quickCheckCard} ${styles.unselectedWorkflowWrapper}`}>
                        {unselectWorkflow.map(item => (
                            <div key={item.category} className={styles.unselectedItem}>
                                {!!item?.itemList.length && <p>{item.categoryName}：</p>}
                                <div className={styles.workflowSortableWrapper}>
                                    {!!item?.itemList.length &&
                                        item?.itemList?.map(d => (
                                            <Tooltip
                                                placement="top"
                                                title={d.itemName}
                                                align={{ offset: [0, 10] }}
                                                key={d.itemId}
                                            >
                                                <div className={styles.workflowSortable}>
                                                    <div className={styles.sortableItem}>
                                                        <span>{d.itemName}</span>
                                                        <Icon.Button
                                                            className={styles.lintGrayColor}
                                                            icon="iconadd_function_o"
                                                            dark
                                                            onClick={() => handleAdd(d, item.category)}
                                                        />
                                                    </div>
                                                </div>
                                            </Tooltip>
                                        ))}
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </Modal>
    );
};

export default QuickCheckModal;
